@echo off

pushd %~dp0

echo * Packing source code

if exist __dist rmdir /S /Q __dist
mkdir __dist

for /F %%i in (VERSION) do set VERSION=%%i
set DIST_NAME=qTeXPre-%VERSION%-src

echo.  [SVN listing]:
svn status -v > __dist\files 2> NUL
if errorlevel 1 (
	echo.    Failed [Can`t find version controlled files]
	goto end
)
echo.    Ok

echo.  [Copying files]:
for /f "eol=? tokens=2* delims=ACDIMRX!~L+SKOTB* " %%i in (__dist\files) do (
	for /f "tokens=1*" %%k in ("%%j") do if not exist "%%l\" (
		xcopy /q /y "%%l" "__dist\%DIST_NAME%\%%l\..\" > NUL 2> NUL
	)
)
echo.    Ok

echo.  [ZIP]:
cd __dist
zip -9 -o -r "..\%DIST_NAME%.zip" "%DIST_NAME%" > NUL
cd ..
echo.    Ok

echo.  [Cleanup]
rmdir /S /Q __dist
echo.    Ok

echo.  Done: %DIST_NAME%.zip

echo * Generating NSIS setup file
echo ; WARNING! All changes made in this file will be lost! > setup\setup.nsi
for /f %%i in (VERSION) do echo !define VERSION %%i >> setup\setup.nsi
for /f "tokens=1-5 delims=. " %%a in (VERSION) do (
	echo !define VER_MAJOR %%a >> setup\setup.nsi
	echo !define VER_MINOR %%b >> setup\setup.nsi
	echo !define VER_REVISION %%c >> setup\setup.nsi
	if "%%d"=="" (
		echo !define VER_BUILD 0 >> setup\setup.nsi
	) else echo !define VER_BUILD %%d >> setup\setup.nsi
	if "%%e"=="" (
		echo !define VER_TYPE '' >> setup\setup.nsi
	) else echo !define VER_BUILD '%%e' >> setup\setup.nsi
	for /f "tokens=3 delims=.-/ " %%f in ('date /t') do (
		echo !define YEAR %%f >> setup\setup.nsi
	)
)
for /f "eol=; tokens=*" %%i in (setup\setup.nsi.template) do (
	if not "%%i"=="" echo %%i >> setup\setup.nsi
)
echo.  Done: setup\setup.nsi

:end
popd